package com.bawei.play.view

import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.SimpleVideoEntity
import com.bawei.common.mvi.BaseMviActivity
import com.bawei.play.R
import com.bawei.play.adapter.PlayVideoAdapter
import com.bawei.play.databinding.ActivityPlayBinding
import com.bawei.play.intent.PlayViewIntent
import com.bawei.play.uistate.PlayUiState
import com.bawei.play.viewmodel.PlayViewModel
import com.bumptech.glide.Glide
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RoutePath.PATH_PLAY_PAGE)
@AndroidEntryPoint
class PlayActivity: BaseMviActivity<ActivityPlayBinding>(){

    @Autowired
    lateinit var videoEntity: SimpleVideoEntity

    @Autowired
    @JvmField
    var typeId: Int = -1

    @Autowired
    @JvmField
    var channelId: String = ""

    private val mViewModel: PlayViewModel by viewModels()

    private var videoList = mutableListOf<SimpleVideoEntity>()
    private lateinit var mVideoAdapter: PlayVideoAdapter
    private var mVideoPlayer: StandardGSYVideoPlayer? = null
    private lateinit var layoutManager: SnapPageLayoutManager

    private var pageIndex = 1
    private var pageSize = 10
    private var mCurrentPageIndex: Int = 0


    override fun getLayoutId(): Int = R.layout.activity_play

    override fun initViews() {
        ARouter.getInstance().inject(this)

        //添加传递过来视频数据，做为第一条数据
        videoEntity?.let { videoList.add(it) }

        mDataBinding.smartRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                loadMoreOrRefreshList()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageIndex += 1
                loadMoreOrRefreshList()
            }
        })

        layoutManager = SnapPageLayoutManager(this@PlayActivity)
        mDataBinding.rvVideo.layoutManager = layoutManager
        mVideoAdapter = PlayVideoAdapter(videoList)

        mVideoAdapter.setOnItemClickListener(object : PlayVideoAdapter.OnItemClickListener{
            override fun onItemChildClick(v: View?, position: Int) {

            }
        })

        mDataBinding.rvVideo.addOnScrollListener(object : RecyclerView.OnScrollListener(){
            //当RV滚动完成时回调
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                mCurrentPageIndex = layoutManager.findFirstVisibleItemPosition()
                videoEntity = videoList[mCurrentPageIndex]
                //通过获取当前Item的ViewHolder对象来获取播放器GSYPlayer
                mVideoPlayer = (mDataBinding.rvVideo.findViewHolderForLayoutPosition(mCurrentPageIndex) as PlayVideoAdapter.VideoPlayViewHolder).dataBinding.gsyPlayer
                if(mVideoPlayer != null){
                    mVideoPlayer?.isLooping = true
                    mVideoPlayer?.startPlayLogic()
                }
            }

            //当RV滚动状态改变是回调
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                //优化：滚动时不加载页面中图片
                if(newState == RecyclerView.SCROLL_STATE_IDLE){
                    Glide.with(this@PlayActivity).resumeRequests() //恢复图片请求
                }else{
                    Glide.with(this@PlayActivity).pauseRequests() //暂停图片请求
                }

                //滚动时释放播放器
                if(mVideoPlayer != null && newState == RecyclerView.SCROLL_STATE_DRAGGING){
                    mVideoPlayer?.release()
                }
            }
        })

        mDataBinding.rvVideo.swapAdapter(mVideoAdapter, true)
    }


    fun loadMoreOrRefreshList() {
        lifecycleScope.launch {
            if(typeId == -1){
                mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
            }else{
                mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
            }
        }
    }

    override suspend fun sendViewIntent() {
        if(typeId == -1){
            mViewModel.channel.send(PlayViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
        }else{
            mViewModel.channel.send(PlayViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
        }
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is PlayUiState.LoadSimpleVideoSuccess -> {
                    mDataBinding.smartRefresh.finishRefresh()
                    var oldListSize = videoList.size
                    //只有在下拉刷新时，且数据大于一条数据，才清理之前的数据，并整体刷新列表
                    if (pageIndex == 1 && oldListSize > 1) {
                        videoList.clear()
                        videoList.addAll(it.list)
                        mVideoAdapter.notifyDataSetChanged() //整体刷新列表
                    } else {
                        videoList.addAll(it.list.filter {entity -> entity.id != videoEntity.id})
                        var startPosition =  if (oldListSize > 1) oldListSize - 1 else 1
                        mVideoAdapter.notifyItemRangeChanged(startPosition, videoList.size - 1)  //指定范围，执行局部刷新
                    }
                }
                is PlayUiState.LoadSimpleVideoFail -> {
                    showToastMsg(it.msg)
                }
                else -> {}
            }
        }
    }

    override fun onResume() {
        if(mVideoPlayer != null){
            mVideoPlayer?.onVideoResume()
        }
        super.onResume()
    }

    override fun onPause() {
        if(mVideoPlayer != null){
            mVideoPlayer?.onVideoPause()
        }
        super.onPause()
    }

    override fun onDestroy() {
        if(mVideoPlayer != null){
            mVideoPlayer?.release()
            mVideoPlayer = null
        }
        super.onDestroy()
    }



}